<?php

class WritingPadComponent extends Object {

    //called before Controller::beforeFilter()
    function initialize(&$controller, $settings = array()) {
        // saving the controller reference for later use
        $this->controller = & $controller;
    }

    //called after Controller::beforeFilter()
    function startup(&$controller) {

    }

    //called after Controller::beforeRender()
    function beforeRender(&$controller) {

    }

    //called after Controller::render()
    function shutdown(&$controller) {

    }

    //called before Controller::redirect()
    function beforeRedirect(&$controller, $url, $status=null, $exit=true) {

    }

    function redirectSomewhere($value) {
        // utilizing a controller method
        $this->controller->redirect($value);
    }

    ////////////////////////////////////////////////////
    /**
     *
     * This class is basically a wrapper around Cake's Session component
     * API:
     *
     * noteDown
     * readPad
     * clearPad
     */
    ////////////////////////////////////////////////////////
//    function isOrderInProcess($order_token) {
//        if (!isset($this->controller->Session->read($order_token))) {
//            return true;
//        } else {
//            return false;
//        }
//    }

    /**
     * returns true if item is already on the order list
     */
    function itemAlreadyExists($order_token, $item) {
        /**
         * Order is an array of [Item Id] => [Quantity]
         */
        $order = $this->readPad($order_token);
        $exists = array_key_exists($item, $order);

        return $exists;
    }

/**
 *
 * @param <type> $order_token
 * @param <type> $item
 * @param <type> $qty
 * @return <type> updated order
 */
    function updateQuantity($order_token, $item, $qty) {
        $order = $this->readPad($order_token);
        $order[$item] = $qty;
        $this->controller->Session->write($order_token, $order);
        return $order;
    }

    /**
     *
     * Writes the $orderedItems variable in the session variable against the key $order_token.
     * 
     * @param <type> $order_token unique order id
     * @param <type> $orderedItems
     */
    function noteDown($order_token, $orderedItems) {

        $ordered_items_list = $this->readPad($order_token);

        //$old_items = explode(",", $ordered_items_list);
        $new_items = explode(",", $orderedItems);
        foreach ($new_items as $item) {
            /**
             * If list is empty simply add the item with quantity = 1
             */
            if (empty($ordered_items_list)) {
                $ordered_items_list[$item] = 1;
            } else {

                /**
                 * If item was already on the order, increase its quantity by 1.
                 */
                if ($this->itemAlreadyExists($order_token, $item)) {
                    $oldQty = $this->getQuantity($order_token, $item);
                    $ordered_items_list = $this->updateQuantity($order_token, $item, $oldQty + 1);
                } else {
                    $ordered_items_list[$item] = 1;
                }
            }
        }
        $this->controller->Session->write($order_token, $ordered_items_list);
    }

    function getQuantity($order_token, $item) {
        $order = $this->readPad($order_token);
        $qty = $order[$item];
        return $qty;
    }

    function getMenuItemDetails($menu_item_id){
        $menu_item_details = $this->requestAction(
                "/menu_items/getNameOfMenuItem/".$menu_item_id);
        
        return $menu_item_details;
        //return $menu_item_details["MenuItem"]["item_name"];//$menu_item_id."_some_name";//$menu_item_details["item_name"];
    }

    /**
     * Returns an associaltive array with following structure
     * array(
     *      [menu_item_id] => array (
     *                              "menu_item_name"=>"whatever is the name",
     *                              "quantity=>3
     *                              )
     * )
     */
    function getHumanReadableOrder($order_token) {
        $temporarilyNotedOrder="Please choose items from menu card.";
        //Order details stored in Session variable against unique $order_token id
        $order = $this->readPad($order_token);
        //debug($order);
        if(is_array($order)){
        $humanReadableOrder = array();
        foreach ($order as $id => $qty) {
            $menu_item_details = $this->getMenuItemDetails($id);
            $humanReadableOrder[$id] = array(
                "from_writingpad_menu_item_id" =>$menu_item_details["MenuItem"]["id"],
                "from_writingpad_menu_item_name" => $menu_item_details["MenuItem"]["item_name"],
                "from_writingpad_quantity" => $qty,
                "from_writingpad_price" =>  $menu_item_details["MenuItem"]["item_base_price"]
            );
        }

        //debug($humanReadableOrder);
        $temporarilyNotedOrder = $humanReadableOrder;

        }
        return $temporarilyNotedOrder;
    }

    /**
     * Reads the temporarily noted order.
     *
     * Returns an associative array of [Item id] => [Quantity]
     * 
     * @param <type> $order_token
     * @return <type>
     */
    function readPad($order_token) {
        $temporarilyNotedOrder = $this->controller->Session->read($order_token);
        return $temporarilyNotedOrder;
    }

    /**
     *
     * @param <type> $order_token
     * @param <type> $itemToRemove item to be removed
     */
    function removeFromPad($order_token, $itemToRemove) {
        //read the order array from the sesion variable.
        $order = $this->readPad($order_token);
        //Following function removes the item from the session variable.
        unset ($order[$itemToRemove]);
        //debug($order);
        $this->controller->Session->write($order_token, $order);
    }

    function clearPad($order_token) {
        //delete is deprecated function. we shoul think of some alternative function
        $this->controller->Session->delete($order_token);
    }

}

?>